import React,{Component} from 'react';
import {createStore, combineReducers} from "redux";

function Action(type, data) {
    return {
        type: type,
        data: data
    }
}

function reducerSave(state = [], action) {
    switch (action.type) {
        case "ADD":
            if (state.filter((item) => item.id === action.data.id).length === 0) {
            return [...state, action.data];
        }
            return state;
    }
}

function reducerDelete(state = [], action) {
    switch (action.type) {
        case "DEL":
            return state.filter((item, idx, ary) => item.id !== action.data.id);
    }
}

function reducerInner(...args) {
    return reducerSave(...args) || reducerDelete(...args) || args[0];
}

// let reducer = combineReducers({reducerSave, reducerDelete});

const store = createStore(reducerInner);

class Oper extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            id: "",
            name: ""
        }
    }

    setId(e) {
        let val = e.target.value;
        this.setState(preState => {
            return {...preState, id: val}
    });
    }

    setName(e) {
        let val = e.target.value;
        this.setState(preState => {
            return {...preState, name: val}
    });
    }

    onAdd() {
        store.dispatch(new Action("ADD", this.state));
    }

    onDel() {
        store.dispatch(new Action("DEL", this.state));
    }

    render() {
        return (<React.Fragment>
            ID: <input type="text" onChange={this.setId.bind(this)}/>
        NAME: <input type="text" onChange={this.setName.bind(this)}/>
        <button onClick={this.onAdd.bind(this)}>增加</button>
        <button onClick={this.onDel.bind(this)}>删除</button>
        </React.Fragment>);
    }
}

class Shower extends Component {
    constructor(props) {
        super(props);
    }

    render() {
        return <div>{this.props.id} {this.props.name}</div>;
    }
}

export default class ReduxDemo extends Component {
    constructor(props) {
        super(props);
        this.show = this.show.bind(this);
        this.state = {num: 0}
    }

    componentDidMount() {
        this.unScribe = store.subscribe(this.show);
    }

    componentWillUnMount() {
        this.unScribe();
    }

    show() {
        this.setState(preState => {
            return {...preState, num: 1 - preState.num};
    });
    }

    render() {
        var showerList = [];
        if (store.getState()) {
            showerList = store.getState().map((item, idx, ary) =>
                <Shower key={item.id} id={item.id} name={item.name}/>
        );
        }
        return (
            <div>
            <Oper/>
            <div>{showerList}</div>
            </div>
    );
    }
}
